<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb :separator-icon="ArrowRight">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>心理测评</el-breadcrumb-item>
			<el-breadcrumb-item>测评结果管理</el-breadcrumb-item>
		</el-breadcrumb>
		<hr />

		<!-- 头部搜索栏 -->
		<div>
			<el-form :inline="true" :model="formInline" class="demo-form-inline">
				<el-form-item label="测评名称">
					<el-input v-model="formInline.psycTestname" placeholder="请输入测评名称" clearable
						@clear="handleClear('assessment')" />
				</el-form-item>

				<el-form-item label="用户名称">
					<el-input v-model="formInline.userName" placeholder="请输入用户名称" clearable
						@clear="handleClear('user')" />
				</el-form-item>

				<el-form-item label="测评时间">
					<el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
						end-placeholder="结束日期" clearable @clear="handleClear('date')" />
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="getData">搜索</el-button>
					<el-button type="danger" @click="batchDelete">批量删除</el-button>
				</el-form-item>
			</el-form>
		</div>

		<!-- 结果详情弹窗 -->
		<el-dialog v-model="detailVisible" title="测评结果详情" width="700px">
			<el-descriptions column="1" border>
				<el-descriptions-item label="测评名称">{{ detailForm.psycTest.name}}</el-descriptions-item>
				<el-descriptions-item label="用户名称">{{ detailForm.sysUser.username }}</el-descriptions-item>
				<el-descriptions-item label="测评分数">{{ detailForm.score }}</el-descriptions-item>
				<el-descriptions-item label="测评时间">{{ formatDateTime(detailForm.time) }}</el-descriptions-item>
				<el-descriptions-item label="测评结论">
					<div style="white-space: pre-line; text-align: left; line-height: 1.6;">
						{{ detailForm.resultContent }}
					</div>
				</el-descriptions-item>
			</el-descriptions>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="detailVisible = false">关闭</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 表格数据展示 -->
		<div>
			<el-table :data="tableData" border @selection-change="handleSelectionChange"
				style="width: 100%; margin-left: 30px; margin-top: 20px;">
				<el-table-column type="selection" width="55" />
				<el-table-column label="ID" width="80">
					<template #default="scope">{{ scope.row.id }}</template>
				</el-table-column>
				<el-table-column property="psycTest.name" label="测评名称" />
				<el-table-column property="sysUser.username" label="用户名称" />
				<el-table-column property="score" label="测评分数" />
				<el-table-column property="time" label="测评时间" :formatter="formatTableDate" />

				<el-table-column label="操作">
					<template #default="scope">
						<el-button type="primary" size="small" @click="showDetail(scope.row)">
							查看详情
						</el-button>
						<el-button type="danger" size="small" @click="deleteItem(scope.row)">
							删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<!-- 分页设置 -->
		<div style="margin: 20px 0 20px 30px;">
			<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
				layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
				@current-change="handleCurrentChange" />
		</div>
	</div>
</template>

<script setup>
	import {
		getCurrentInstance,
		onMounted,
		reactive,
		ref
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import {
		ArrowRight
	} from '@element-plus/icons-vue'

	// 搜索表单数据
	const formInline = reactive({
		psycTestname: '',
		userName: '',
	})

	// 日期范围
	const dateRange = ref([])

	// 测评列表数据
	/* 	const assessmentList = reactive([]) */

	// 表格数据
	const tableData = reactive([])

	// 分页相关
	const currentPage = ref(1)
	const pageSize = ref(10)
	const total = ref(0)

	// 详情弹窗相关
	const detailVisible = ref(false)
	const detailForm = reactive({
		psycTest: {},
		sysUser: {},
		score: '',
		time: '',
		resultContent: ''
	})

	// 批量选择数据
	const multipleSelection = ref([])

	// 获取axios实例
	const axios = getCurrentInstance().appContext.config.globalProperties.axios

	// 页面挂载时加载数据
	onMounted(() => {
		getData()
	})

	// 获取测评列表数据（用于下拉选择）
	/* 	const getAssessmentList = () => {
			axios.get('evaluation')
				.then((resp) => {
					assessmentList.splice(0, assessmentList.length, ...resp.data)
				})
				.catch((error) => {
					console.error('获取测评列表失败:', error)
					ElMessage.error('获取测评列表失败，请稍后再试')
				})
		} */

	// 获取测评结果数据
	const getData = () => {
		// 处理日期参数
		const startDate = dateRange.value[0] ? new Date(dateRange.value[0]).toISOString() : ''
		const endDate = dateRange.value[1] ? new Date(dateRange.value[1]).toISOString() : ''

		axios.get(
				`psycTestResult/page?sysUser.username=${formInline.userName}&psycTest.name=${formInline.psycTestname}`, {
					params: {
						startTime: startDate,
						endTime: endDate,
						pageNum: currentPage.value,
						pageSize: pageSize.value
					}
				})
			.then((resp) => {
				total.value = resp.data.total
				tableData.splice(0, tableData.length, ...resp.data.list)
			})
			.catch((error) => {
				console.error('获取测评结果失败:', error)
				ElMessage.error('获取测评结果失败，请稍后再试')
			})
	}

	// 清除搜索条件
	const handleClear = (type) => {
		if (type === 'assessment') {
			formInline.assessmentId = ''
		} else if (type === 'user') {
			formInline.userName = ''
		} else if (type === 'date') {
			dateRange.value = []
		}
		getData()
	}

	// 分页相关方法
	const handleSizeChange = (val) => {
		pageSize.value = val
		getData()
	}

	const handleCurrentChange = (val) => {
		currentPage.value = val
		getData()
	}

	// 显示详情
	const showDetail = (row) => {
		detailVisible.value = true
		resultContent: ''
		// 填充详情表单数据
		axios.get(
				`psycTestResult/${row.id}`)
			.then((resp) => {
				console.log(resp);
				Object.assign(detailForm,resp.data)
				
			})
			.catch((error) => {
				console.error('获取测评结果失败:', error)
				ElMessage.error('获取测评结果失败，请稍后再试')
			})
	}

	// 处理选择变化
	const handleSelectionChange = (val) => {
		multipleSelection.value = val
	}

	// 单个删除
	const deleteItem = (row) => {
		ElMessageBox.confirm(
				'此操作将永久删除该测评结果，是否继续？',
				'提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
			.then(() => {
				axios.delete(`assessment_result/${row.id}`)
					.then((resp) => {
						if (resp.code === 200) {
							ElMessage({
								type: 'success',
								message: '删除成功'
							})
							getData()
						} else {
							ElMessage.error(resp.message || '删除失败')
						}
					})
					.catch((error) => {
						console.error('删除失败:', error)
						ElMessage.error('删除失败，请稍后再试')
					})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '已取消删除'
				})
			})
	}

	// 批量删除
	const batchDelete = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请选择要删除的测评结果')
			return
		}

		ElMessageBox.confirm(
				`此操作将永久删除选中的${multipleSelection.value.length}条测评结果，是否继续？`,
				'提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			)
			.then(() => {
				const ids = multipleSelection.value.map(item => item.id).join(',')
				axios.delete(`assessment_result?ids=${ids}`)
					.then((resp) => {
						if (resp.code === 200) {
							ElMessage({
								type: 'success',
								message: '批量删除成功'
							})
							getData()
							multipleSelection.value = []
						} else {
							ElMessage.error(resp.message || '批量删除失败')
						}
					})
					.catch((error) => {
						console.error('批量删除失败:', error)
						ElMessage.error('批量删除失败，请稍后再试')
					})
			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '已取消删除'
				})
			})
	}

	// 格式化日期时间
	const formatDateTime = (dateString) => {
		if (!dateString) return ''
		const date = new Date(dateString)
		return date.toLocaleString('zh-CN', {
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit'
		})
	}

	// 表格中日期格式化
	const formatTableDate = (row, column, cellValue) => {
		return formatDateTime(cellValue)
	}
</script>

<style scoped>
	.demo-form-inline .el-input,
	.demo-form-inline .el-select,
	.demo-form-inline .el-date-picker {
		--el-input-width: 220px;
		margin-right: 10px;
	}

	.el-descriptions__item-label {
		font-weight: bold;
	}

	.el-descriptions__item-content {
		text-align: left;
	}
</style>